import os
import json
import pymysql
import logging
from dotenv import load_dotenv

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)

# 加载环境变量
load_dotenv()

# 获取MySQL连接配置
mysql_host = os.getenv('MYSQL_HOST', 'localhost')
mysql_port = int(os.getenv('MYSQL_PORT', 3306))
mysql_user = os.getenv('MYSQL_USER', 'root')
mysql_password = os.getenv('MYSQL_PASSWORD', '')
mysql_database = os.getenv('MYSQL_DATABASE', 'zsxq_group')


def check_database():
    """检查MySQL数据库中的帖子数据"""
    logger.info("=== 开始检查MySQL数据库内容 ===")
    
    try:
        # 连接数据库
        conn = pymysql.connect(
            host=mysql_host,
            port=mysql_port,
            user=mysql_user,
            password=mysql_password,
            database=mysql_database,
            connect_timeout=10
        )
        
        logger.info(f"成功连接到MySQL数据库: {mysql_database}")
        
        # 创建游标
        cursor = conn.cursor()
        
        # 检查topics表中的记录数
        cursor.execute("SELECT COUNT(*) FROM topics")
        topics_count = cursor.fetchone()[0]
        logger.info(f"topics表中的记录数: {topics_count}")
        
        # 如果有记录，显示最近的5条记录
        if topics_count > 0:
            cursor.execute("SELECT topic_id, type, create_time FROM topics ORDER BY create_time DESC LIMIT 5")
            recent_topics = cursor.fetchall()
            logger.info("最近的5条帖子记录:")
            for topic in recent_topics:
                logger.info(f"- {topic}")
        
        # 检查images表中的记录数
        cursor.execute("SELECT COUNT(*) FROM images")
        images_count = cursor.fetchone()[0]
        logger.info(f"images表中的记录数: {images_count}")
        
        # 检查files表中的记录数
        cursor.execute("SELECT COUNT(*) FROM files")
        files_count = cursor.fetchone()[0]
        logger.info(f"files表中的记录数: {files_count}")
        
        logger.info("=== 数据库检查完成 ===")
        
    except Exception as e:
        logger.error(f"检查数据库时出错: {str(e)}")
    finally:
        # 关闭连接
        if 'cursor' in locals():
            cursor.close()
        if 'conn' in locals():
            conn.close()
            logger.info("MySQL数据库连接已关闭")


if __name__ == '__main__':
    check_database()